<template>
  <div>
    <el-container>
      <el-header><Header></Header></el-header>
      <el-main>
        <div id="title">创建账号</div>
        <el-form ref="regform" 
          :model="regform"
          :rules="rules" >
          <el-row type="flex" justify="center">
            <el-col :span="4">
              <el-form-item prop="username">
                <el-input v-model="regform.username" prefix-icon="el-icon-user" placeholder="用户名"></el-input>
              </el-form-item>
            </el-col>
          </el-row>
          <el-row type="flex" justify="center">
            <el-col :span="4">
              <el-form-item prop="password">
                <el-input v-model="regform.password" prefix-icon="el-icon-lock" show-password placeholder="密码"></el-input>
              </el-form-item>
            </el-col>
          </el-row>
          <el-row type="flex" justify="center">
            <el-col :span="4">
              <el-form-item prop="checkPass">
                <el-input v-model="regform.checkPass" prefix-icon="el-icon-lock" show-password placeholder="确认密码"></el-input>
              </el-form-item>
            </el-col>
          </el-row>
          <el-row type="flex" justify="center">
            <el-col :span="4">
              <el-form-item prop="tel">
                <el-input v-model="regform.tel" prefix-icon="el-icon-phone-outline" placeholder="电话"></el-input>
              </el-form-item>
            </el-col>
          </el-row>
          <el-row type="flex" justify="center">
            <el-col :span="4">
              <el-form-item prop="email">
                <el-input v-model="regform.email" prefix-icon="el-icon-message" placeholder="邮箱"></el-input>
              </el-form-item>
            </el-col>
          </el-row>
          <el-row type="flex" justify="center">
            <el-col :span="4">
              <el-form-item prop="verifyCode">
               <div class="identifybox">
                  <el-input v-model="regform.verifyCode" prefix-icon="el-icon-key" placeholder="验证码"></el-input>
                  <div @click="refreshCode">
                    <s-identify :identifyCode="identifyCode"></s-identify>
                  </div>
                </div>
              </el-form-item>
            </el-col>
          </el-row>
          <el-row type="flex" justify="center">
            <el-col :span="4">
              <el-form-item>
                <el-button type="primary" round @click="submitForm('regform')">注册</el-button>
              </el-form-item>
              <el-link type="primary" @click="dologin">已有账号？立即登录></el-link>
            </el-col>
          </el-row>
        </el-form>
      </el-main>
      <el-footer height="120px"><Footer></Footer></el-footer>
    </el-container>
  </div>
</template>

<script>


import Header from "@/components/Header";
import Footer from "@/components/Footer";
import SIdentify from "@/components/identify/identify";
export default {
  name: "register",
  components: {Footer, Header, SIdentify},
  mounted() {
    // 验证码初始化
    this.identifyCode = ''
    this.makeCode(this.identifyCodes, 4)
  },
  data() {
    
    let checkEmail = (rule, value, callback) => {
      if (value === '') {
          callback(new Error('请输入邮箱'))
      } else if (!this.checkRemail(value)) {
          callback(new Error('邮箱地址不合法，请重新输入'))
      } else {
          callback()
      }
    }
    let checkTel = (rule, value, callback) => {
      if (value === '') {
          callback(new Error('请输入手机号码'))
      } else if (!this.checkMobile(value)) {
          callback(new Error('手机号码不合法，请重新输入'))
      } else {
          callback()
      }
    }
    let checkVerifycode = (rule, value, callback) => {
      if (value === '') {
          callback(new Error('请输入验证码'))
      } else if (value !== this.identifyCode) {
          console.log ('validateVerifycode',value)
          callback(new Error('验证码不正确！'))
      } else {
          callback()
      }
    }    
    // <!--验证密码-->
    let validatePass = (rule, value, callback) => {
      if (value === "") {
        callback(new Error("请输入密码"))
      } else {
        if (this.regform.checkPass !== "") {
          this.$refs.regform.validateField("checkPass");
        }
        callback()
      }
    }
    // <!--二次验证密码-->
    let validatePass2 = (rule, value, callback) => {
      if (value === "") {
        callback(new Error("请再次输入密码"));
      } else if (value !== this.regform.password) {
        callback(new Error("两次输入密码不一致!"));
      } else {
        callback();
      }
    };
    return {
      regform: {
        username: '',
        password: '',
        checkPass: '',
        tel: '',
        email: '',
        verifyCode: ''
      },
      identifyCodes: '1234567890',
      identifyCode: '',
      rules: {
        username: [{ required: true, message: '请输入用户名', trigger: 'blur'}],
        email: [{ validator: checkEmail, message: '', trigger: 'change' }],
        password: [{ validator: validatePass, message:'', trigger: 'change' }],
        checkPass: [{ validator: validatePass2, message:'', trigger: 'change' }],
        tel: [{ validator: checkTel, message:'', trigger: 'change' }],
        verifyCode: [{ validator: checkVerifycode, message:'', trigger: 'blur' }],
      }
    }
  },
  methods: {

    dologin(){
      this.$router.push({
        path: "/login"
      });
    },
    // <!--提交注册-->
    submitForm(formName) {
      let fd = new FormData();
      fd.append("userName",this.regform.username);
      fd.append("passwd",this.regform.password);
      fd.append("email",this.regform.email);
      fd.append("telphone",this.regform.tel);


      let config = {
        headers: {
          'Content-Type': 'multipart/form-data'
        }
      }
      this.$refs[formName].validate(valid => {
        if(valid){
          this.$axios.post("user/login/register", fd, config).then(res => {
            alert(res.data.msg)
            if(res.data.msg === "注册成功")
            {
              this.$router.push({path:'/login'})
              console.log(res.data)
            }

          }).catch(res => {
            // alert(res?.data?.msg)
            alert(res.data.msg)
          })
        }else{
          // console.log("注册失败")
          alert("注册失败，请检查输入信息")
        }
      })
    },
    // 验证手机号
    checkMobile(str) {
      let re = /^1\d{10}$/
      if (re.test(str)) {
        return true;
      } else {
        return false;
      }
    },
    // 验证邮箱
    checkRemail(str) {
      let re = /^(([^<>()[\]\\.,;:\s@"]+(\.[^<>()[\]\\.,;:\s@"]+)*)|(".+"))@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))$/;
      if (re.test(str)) {
        return true;
      } else {
        return false;
      }
    },
    // 切换验证码
    refreshCode() {
      this.identifyCode = ''
      this.makeCode(this.identifyCodes, 4)
    },
    // 生成四位随机验证码
    makeCode(o, l) {
      for (let i = 0; i < l; i++) {
        this.identifyCode += this.identifyCodes[
          this.randomNum(0, this.identifyCodes.length)
        ]
      }
      console.log(this.identifyCode)
    },
    // 生成随机数
    randomNum(min, max) {
      return Math.floor(Math.random() * (max - min) + min)
    },
  },
}
</script>

<style scoped>
.identifybox{
  display: flex;
  justify-content: space-between;
  margin-top:7px;
}
.el-button {
  background: #3A62D7;
  border: #3A62D7;
  width: 100%;
  color: #F5F5F5;
}
.el-row {
  margin-top: 30px;
  margin-bottom: 20px;
}

#title {
  color: #F5F5F5;
  font-size: 30px;
  font-weight: bold;
  border: #333333;
  margin-top: 50px;
  margin-bottom: 20px;
}

#bg {
  background: url("../assets/bg.png") center center no-repeat;
  background-size: contain;
  position: absolute
}

.s2{    /*s2是我的输入框class*/
}
/deep/ .el-input__inner { /*或者 .s2>>>.el-input__inner  */
  border-radius: 20px; /*输入框圆角值*/
  background-color: rgba(255, 255, 255, 0.35);
  border: rgba(255, 255, 255, 0.35);
  color: #F5F5F5;
}

/deep/ .el-input__prefix {
  color: #F5F5F5;
}

.el-header{
  background-color: #F5F5F5;
  color: #333;
  text-align: center;
  line-height: 60px;
}
.el-footer {
  background-color: #F5F5F5;
  color: #333;
  text-align: center;
  line-height: 3px;

}

.el-aside {
  background-color: #D3DCE6;
  color: #333;
  text-align: center;
  line-height: 150px;
}

.el-main {
  background: url("../assets/bg.png") center center no-repeat;
  background-size: 100% 100%;
  /*background-color: #E9EEF3;*/
  color: #333;
  text-align: center;
  height: 800px;
  padding: unset;
}

body > .el-container {
  margin-bottom: 40px;
}

.el-container:nth-child(5) .el-aside,
.el-container:nth-child(6) .el-aside {
  line-height: 260px;
}

.el-container:nth-child(7) .el-aside {
  line-height: 320px;
}
</style>